import { CONSTANT } from '@/utils/constant'
import { useUserAllStore } from './all/store'
import { useUserInteractiveStore } from './interactive/store'
import { useUserOftenStore } from './often/store'
import { TranslatorAllToSimple, setSearchStatusInSimple } from './utils'
import { useUserStore } from './store'

/**取消会议rtc接入 */
export const resetProtocolNotRtc = () => {
	const tree = useUserAllStore.getState().tree
	const often = useUserOftenStore.getState().list
	const interactive = useUserInteractiveStore.getState().list

	let _list = [...tree, ...often, ...interactive]
	_list.forEach((x) => {
		if (x.mcc.protocol === CONSTANT.callType.RTC) {
			//原来是rtc呼叫，需要改掉. 如果原来是ip 那就走 h323，否则就是 auto
			if (x.mcc.account_type === CONSTANT.accountType.IP || x.mcc.account_type === CONSTANT.accountType.e164Ip) {
				x.mcc.protocol = CONSTANT.callType.H323
			} else {
				x.mcc.protocol = CONSTANT.callType.AUTO
			}
		}
	})
	useUserAllStore.setState({ tree: [...tree] })
	useUserOftenStore.setState({ list: [...often] })
	useUserInteractiveStore.setState({ list: [...interactive] })
}

/**会议码率变更 修改终端码率 */
export const resetBitrate = (oldBit: number, newBit?: number) => {
	const tree = useUserAllStore.getState().tree
	const often = useUserOftenStore.getState().list
	const interactive = useUserInteractiveStore.getState().list

	let _list = [...tree, ...often, ...interactive]
	_list.forEach((x) => {
		if (x.mcc.account_type !== 10 && x.mcc.account_type !== 2) {
			if (newBit != null && x.mcc.bitrate != null) {
				if (newBit > oldBit) {
					if (x.mcc.bitrate === oldBit) {
						x.mcc.bitrate = newBit
					}
				} else {
					if (x.mcc.bitrate > newBit) {
						x.mcc.bitrate = newBit
					}
				}
			}
		}
	})
	useUserAllStore.setState({ tree: [...tree] })
	useUserOftenStore.setState({ list: [...often] })
	useUserInteractiveStore.setState({ list: [...interactive] })
}

/**
 * 超大方切换需要直接强制默认所有终端都是互动终端； 并且变成简单级联（changeCascadeInUser）
 * 调用changeCascadeInUser时，全部终端已经是最新，此时常用终端会根据全部终端刷新，所以在超大方时候有终端移除也能感知
 * */
export const setAll2Interactive = () => {
	const tree = useUserAllStore.getState().tree
	let result = []
	for (const item of tree) {
		if (item.mcc.account_type !== 10) {
			item.status.isInteractive = true
			item.mcc.interactive_mt = 1
			result.push(item)
		}
	}
	useUserAllStore.setState({ tree: [...tree] })

	const keywords = useUserStore.getState().keywords
	let list = TranslatorAllToSimple(result)
	setSearchStatusInSimple(list, keywords)
	useUserInteractiveStore.setState({ list })
}
